package com.hollycrm.hollysqm.handle.rest;

import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hollycrm.hollysqm.handle.service.factory.PlanChainManager;

/**
 * 提供REST服务的访问控制器
 * @author jianglong
 * @date 2017年5月23日 上午10:55:32
 */
@Scope("prototype")
@RestController
@RequestMapping("/handle/rest")
public class HandleAction {
	
	private static final Logger log = LoggerFactory.getLogger(HandleAction.class);

	@Autowired
	private PlanChainManager planChainManager;
		
	
	/**
	 * 提供执行质检计划抽取的Rest接口
	 * @param planId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/executePlan")	
	public void executePlan(@RequestParam("planId") String planId,HttpServletRequest request,HttpServletResponse response){
		System.out.println("访问IP:"+request.getRemoteAddr());
		log.info("开始执行质检【"+planId+"】计划...");
		String msg = "";
		long sTime = System.currentTimeMillis();
		PrintWriter out = null;
		try{
			out = response.getWriter();
			if (StringUtils.isBlank(planId)){
				log.error("调用质检抽取服务的参数为空，计划ID【"+planId+"】...");
				msg = "fial_"+System.currentTimeMillis();
				out.print(msg);
				out.flush();
				out.close();
			}else {
				msg = "ok_"+System.currentTimeMillis();
				out.print(msg);
				out.flush();
				out.close();
				planChainManager.excute(planId);
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("当前质检计划执行异常，计划ID【"+planId+"】...",e);
			msg = "err_"+System.currentTimeMillis();
			out.print(msg);
			out.flush();
			out.close();
		}finally{
			long eTime = System.currentTimeMillis();
			log.info("结束执行质检【"+planId+"】计划，用时：【"+((eTime-sTime)/1000)+"s】...");
		}
	}
	
	@RequestMapping("/testPlan")	
	public void testPlan(){
		Random r=new Random();
		int n = r.nextInt(10);
		String name = "name_"+System.currentTimeMillis();
		System.out.println("action:"+name+"\t"+n);
		planChainManager.setTestCout(n);
		planChainManager.getTestCout(name);
	}
			
	
}
